<?php
// +----------------------------------------------------------------------
// | Author: 发仔 <i@fazi.me> 
// +----------------------------------------------------------------------

namespace app\admin\controller;

use think\Db;

class Menu extends Base
{
	protected $beforeActionList = ['tree'];
	
	public function index() {

		$this->assign('tree',$this->tree);
		return $this->out();
		
	}
	
	
	public function add() {
		
		if(request()->isPost()) {
			
			$data = $this->data();
			$rslt = Db::name('menu')->insert($data);
			cache('menus',null);
			return $this->res($rslt,'添加成功','menu/index');
		}
		
		//选项 
		$this->assign('pids', TplOptions($this->tree,'','name','id'));
		
		return $this->out();
		
	}
	
	public function edit() {
		
		$id = input('param.id/d');
		
		if(!$id) {
			return $this->error('入口非法，请重试');
		}
		//提交
		if(request()->isPost()) {
			
			$data = $this->data();
			
			$rslt = Db::name('menu')->where('id',$id)->update($data);
			
			cache('menus',null);
			
			return $this->res($rslt,'','menu/index');
			
		}
		
		$item = Db::name('menu')->find($id);
		//选项
		$this->assign('item',$item);
		$this->assign('pids', TplOptions($this->tree,$item['pid'],'name','id'));
		
		return $this->out('add');
		
	}
	
	//处理数据
	protected function data() {
		
		$P = input('post.');
		$data = [
			'name' => trim($P['name']),
			'url' => trim($P['url']),
			'pid' => $P['pid'],
			'icon' => trim($P['icon']),
		];
		
		return $data;
	}
	
	protected function tree() {
		
		$list = Db::name('menu')->select();
		$this->tree = Arr2Sibling($list);
	}
}   